import os
import sys

from PyQt5.QtWidgets import QWidget, QLabel, QHBoxLayout, QVBoxLayout, QPushButton, QTextEdit, QTableWidget, QTableWidgetItem, QCheckBox, QGridLayout, QApplication, QHeaderView
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

import time, threading

from spider import carSpider


class TransactionDetial(QWidget):

    code_list = []
    right_list = []
    right_botton_list = []
    stop_time = False
    t = ''
    status = ''
    has_fresh = False
    loop_start = True

    def cycle_post(self):
        # FIXME: timeout结束线程 正常结束
        print("-------------------------------------------进入线程")
        self.t = threading.Thread(target=self.loop, name='LoopThread')
        self.t.start()
        print("退出线程-------------------------------------------")

    def loop(self):
        while self.loop_start:
            if not self.is_stop_cycle:
                is_break, sleep_time = self._cycle_post()
                # if is_fresh:
                    # self.freshDataTimer()
                if is_break:
                    # TODO: 11次 炸了 这里可以通知界面
                    self.loop_start = False
                else:
                    print('开始睡觉%s'%sleep_time)
                    time.sleep(sleep_time)
            else:
                print('停止交易')

    def _cycle_post(self):
        # rule_list checkbox选择列表
        print('界面调用开奖结果')
        # serial, number_list, add_record_list = self.car._get_lottery_res()
        self.has_fresh = False  # 是否更新了数据

        # # 更新左下数据
        print('更新左下数据')
        history_number_list = self.car.set_history_data()


        # 更新右下开奖数据 最新数据
        print("更新右下开奖数据 最新数据")
        print(self.car.add_record_list)
        self.car.add_record_list.reverse()
        for index, record in enumerate(self.car.add_record_list): # WARING: right_botton_list已经倒序
            print('开始局部更新################################################################')
            self.addupdate_right_boot = True
            self.right_botton_list[index]['open'] = record[6]
            self.right_botton_list[index]['caculate'] = record[7]


        self.code_list = []
        for code, value in history_number_list.items():
            number = ''
            for i in value[0]:
                number += str(i)
            self.code_list.append({'code': str(int(code)), 'number': number, 'money': value[1]})
        # self.freshLeftDom()

        # TODO: 走后端时间控制
        left_time, left_second = self.car.get_left_time()
        self.prefit2 = float(self.car.win_money)
        if left_time and left_second - 10 > 0:  # 还没有封盘，并且剩余时间大于10秒 下单
            print('界面进入下单')
            lost, rule_list, msg_list = self.car.follow_rules(self.rule_list)
            # 更新右上盈利
            print('更新右上盈利')
            print(rule_list)
            self.prefit = 0
            for index, rule in enumerate(rule_list):
                self.right_list[index]['prefit'] = rule[4]
                self.prefit = self.prefit+float(rule[4])
            # self.freshRightTop()
                print(rule[4])
            if lost:
                self.status = True
                return True, 0

            # 插入新的record
            self.right_botton_list.reverse()  # 反转过来插入

            for msg in msg_list:
                # msg = msg.split(',')
                print('开始全局更新################################################################')
                self.allupdate_right_boot = True
                self.right_botton_list.append(
                    {'qihao': msg[0], 'code': msg[1], 'position': msg[2], 'number': msg[3], 'money': '',
                     'one': msg[4], 'count': msg[5], 'state': '下注成功', 'open': msg[6], 'caculate': msg[7], 'mode': '跟踪球号'})

            self.right_botton_list.reverse()  # 反转
                # self.freshDataTimer()
            self.has_fresh = True  # 更新了数据
            print(self.right_botton_list)

        left_time, left_second = self.car.get_left_time()
        if left_time:
            self.signalSecond = left_second + 55  # 设置下次运行的时间
        else:
            self.signalSecond = left_second + 25  # 设置下次运行的时间
        self.status = False
        print('准备下次循环')
        self.update()
        return False, self.signalSecond

    def __init__(self, the_code, username, password, key):
        try:
            super(TransactionDetial, self).__init__()

            self.car = carSpider(the_code, username, password, key)
            self.username = username
            self.car.set_history_data()
            self.rule_list=[]
            self.right_list_msg=[]
            self.prefit = 0.0
            self.prefit2 = 0.0
            self.is_stop_cycle = False
            self.addupdate_right_boot = False
            self.allupdate_right_boot = False
        except Exception as exc:
            print(exc)
        history_number_list = self.car.history_number_list
        for code, value in history_number_list.items():
            number = ''
            for i in value[0]:
                number += str(i)
            self.code_list.append({'code': str(int(code)), 'number': number, 'money': value[1]})
        print(self.code_list)

        origin_rule_list = self.car.origin_rule_list
        for code, rule in enumerate(origin_rule_list):
            print(rule[0], rule[1], rule[2])
            self.right_list.append({'code':code+1, 'state':'ok', 'ball_number':rule[0], 'number':rule[1], 'prefit':'0', 'beitou': rule[2], 'check': 0})
            self.rule_list.append(int(code))
        self.right_botton_list=[]

        self.main_layuot = QHBoxLayout()
        self.left_layout = QVBoxLayout()
        self.right_layout = QVBoxLayout()
        self.main_layuot.setContentsMargins(10, 10, 10, 10)

        self.initUserInfo()
        self.initRightTable()
        self.initLeftTable()
        self.initRightBottonTable()
        self.main_layuot.addLayout(self.left_layout,3)
        self.main_layuot.addLayout(self.right_layout,10)
        self.setLayout(self.main_layuot)
        self.signalSecond = 10000
        self.showMaximized()
        # self.timer = QTimer(self)  # 初始化一个定时器
        # self.timer.timeout.connect(self.freshDataTimer)


    def initUserInfo(self):
        self.user_grid_layout = QGridLayout()

        self.account_lb = QLabel(u"账号：（%s）" % (self.username))
        self.account_lb.setFont(QFont("song", 9, QFont.Bold))

        self.maney_lb = QLabel("余额：（0）")
        self.maney_lb.setFont(QFont("song", 9, QFont.Bold))

        self.liushui_lb = QLabel("流水：0")
        self.liushui_lb.setFont(QFont("song", 9, QFont.Bold))

        self.yingk_lb = QLabel("盈亏：0")
        self.yingk_lb.setFont(QFont("song", 9, QFont.Bold))

        self.time_lb = QLabel("延时 0 秒后开始下注")
        self.time_lb.setFont(QFont("song", 9, QFont.Bold))

        self.zhiying_qhl = QHBoxLayout()
        self.zhikui_qhl = QHBoxLayout()
        yingk_qhl = QHBoxLayout()

        zhiying_lb = QLabel("止盈")
        self.zhiying_qte = QTextEdit()
        self.zhiying_qte.setFixedHeight(27)
        self.zhiying_qte.setFixedWidth(80)
        self.zhiying_qhl.addWidget(zhiying_lb)
        self.zhiying_qhl.addWidget(self.zhiying_qte)
        self.zhiying_qhl.setSpacing(0)

        zhikui_lb = QLabel("止亏")
        self.zhikui_qte = QTextEdit()
        self.zhikui_qte.setFixedHeight(27)
        self.zhikui_qte.setFixedWidth(80)


        self.zhikui_qhl.addWidget(zhikui_lb)
        self.zhikui_qhl.addWidget(self.zhikui_qte)
        self.zhikui_qhl.setSpacing(0)

        yingk_qhl.addLayout(self.zhiying_qhl)
        yingk_qhl.addLayout(self.zhikui_qhl)
        yingk_qhl.setSpacing(60)


        self.user_grid_layout.addWidget(self.account_lb, 0, 0, 1, 1)
        self.user_grid_layout.addWidget(self.maney_lb, 0, 1, 1, 1)
        self.user_grid_layout.addWidget(self.liushui_lb, 1, 0, 1, 1)
        self.user_grid_layout.addWidget(self.yingk_lb, 1, 1, 1, 1)
        self.user_grid_layout.addWidget(self.time_lb, 2, 0, 1, 1)

        bottomHbox = QHBoxLayout()
        bottomHbox.setSpacing(5)

        self.gj_btn = QPushButton("挂机")
        self.gj_btn.setFixedWidth(80)
        self.gj_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        self.gj_btn.clicked.connect(self.start_cycle)
        self.tz_btn = QPushButton("停止")
        self.tz_btn.setFixedWidth(80)
        self.tz_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        self.tz_btn.clicked.connect(self.stop_cycle)
        bottomHbox.addWidget(self.gj_btn)
        bottomHbox.addWidget(self.tz_btn)

        self.user_main = QVBoxLayout()
        self.user_main.addLayout(self.user_grid_layout)
        self.user_main.addLayout(yingk_qhl)
        self.user_main.addLayout(bottomHbox)
        self.left_layout.addLayout(self.user_main,1)

    def start_cycle(self):
        # 启动线程
        self.is_stop_cycle = False
        self.loop_start = True
        self.gj_btn.setEnabled(False)
        self.gj_btn.setStyleSheet(
            "QWidget{ background:#D1D1D1;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        self.cycle_post()

    def stop_cycle(self):
        # 结束线程
        self.is_stop_cycle = True
        self.loop_start = False
        self.gj_btn.setEnabled(True)
        self.gj_btn.setStyleSheet(
            "QWidget{ background:#169bef;color: white;font-size:18px;border: 1px solid white;font-weight: bold;border-width: 0px;border-color: #141529;border-style: solid;border-radius:5;}")
        # TODO: 最后一次不下单的话 中奖判断
        # 获取时间 启线程 获取开奖结果 如果 start 被启动 这个线程再见
        self.th_last_winning()

    def th_last_winning(self):
        print("-------------------------------------------进入last线程")
        self.t = threading.Thread(target=self.last_winning, name='LoopThread')
        self.t.start()
        print("退出last线程-------------------------------------------")

    def last_winning(self):
        # 最后一次不下单的话 中奖判断
        left_time, left_second = self.car.get_left_time()
        if left_time:
            signalSecond = left_second + 55  # 设置下次运行的时间
        else:
            signalSecond = left_second + 25  # 设置下次运行的时间
        time.sleep(signalSecond)
        if not self.loop_start:
            rule_list = self.car.adjust_winning(self.rule_list)
            print('更新右上盈利')
            print(rule_list)
            self.prefit = 0
            for index, rule in enumerate(rule_list):
                self.right_list[index]['prefit'] = rule[4]
                self.prefit = self.prefit+float(rule[4])
                # print(rule[4])

    def paintEvent(self, e):

        self.freshRightTop()
        self.updateLeftTop()
        self.freshLeftDom()
        self.update_left_bottom_view()

    def updateLeftTop(self):
        self.yingk_lb.setText('盈亏：网站统计:' + str(round(self.prefit2,2)) + '  本地统计：'+ str(round(self.prefit,2)))
        self.account_lb.setText(u"账号：（%s）" % (self.username))
        self.maney_lb.setText(u'余额：（%s）' % (self.car.left_money))

    def initLeftTable(self):

        self.stockDetailList = QTableWidget()  # '期号', '号码', '余额'
        stockDetaihorizontalHeader = ['期号', '号码', '余额']
        self.LeftTableHeaderCode = ['code', 'number', 'money']
        self.stockDetailList.setColumnCount(len(stockDetaihorizontalHeader))
        self.stockDetailList.setRowCount(len(self.code_list))
        self.stockDetailList.setHorizontalHeaderLabels(stockDetaihorizontalHeader)
        self.stockDetailList.verticalHeader().setVisible(False)  # 隐藏垂直表头

        self.stockDetailList.setEditTriggers(QTableWidget.NoEditTriggers)
        # self.stockDetailList.setSelectionBehavior(QTableWidget.SelectRows)
        self.stockDetailList.setSelectionMode(QTableWidget.SingleSelection)
        for tmp_table_row in range(self.stockDetailList.rowCount()):
            for tmp_columncount  in range(self.stockDetailList.columnCount()):
                self.stockDetailList.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(str(self.code_list[tmp_table_row][self.LeftTableHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.stockDetailList.setItem(tmp_table_row, tmp_columncount, item)

        self.layout3 = QHBoxLayout()
        self.layout3.setAlignment(Qt.AlignVCenter)  # 垂直居中
        self.layout3.setContentsMargins(0, 0, 0, 0)
        self.layout3.addWidget(self.stockDetailList)
        self.left_layout.addLayout(self.layout3,3)

    def initRightTable(self):
        self.right_top_list_view = QTableWidget()
        stockDetaihorizontalHeader = ['编号', '状态', '球号', '号码', '盈亏', '倍投']
        self.right_topHeaderCode = ['code', 'state', 'ball_number', 'number', 'prefit', 'beitou']
        self.right_top_list_view.setColumnCount(len(stockDetaihorizontalHeader))
        self.right_top_list_view.setRowCount(len(self.right_list))
        self.right_top_list_view.setHorizontalHeaderLabels(stockDetaihorizontalHeader)
        self.right_top_list_view.verticalHeader().setVisible(False)  # 隐藏垂直表头

        self.right_top_list_view.setEditTriggers(QTableWidget.NoEditTriggers)
        # self.stockDetailList.setSelectionBehavior(QTableWidget.SelectRows)
        self.right_top_list_view.setSelectionMode(QTableWidget.SingleSelection)
        for tmp_table_row in range(self.right_top_list_view.rowCount()):
            for tmp_columncount in range(self.right_top_list_view.columnCount()):
                self.right_top_list_view.setRowHeight(tmp_table_row, 25)
                tmp_widget = QWidget()
                tmpLayout = QHBoxLayout()
                if tmp_columncount == 1:
                    check = int(self.right_list[tmp_table_row].get('check',1))
                    cb_btn = MyCheckBox()
                    tmpLayout.addWidget(cb_btn)
                    cb_btn.setrowNo(tmp_table_row)
                    cb_btn.clicked.connect(self.changeTitle)
                    if check == 0:
                        cb_btn.setChecked(True)
                    else:
                        cb_btn.setChecked(False)
                    tmpLayout.setAlignment(Qt.AlignHCenter)
                    tmpLayout.setContentsMargins(0, 0, 0, 0)
                    tmp_widget.setLayout(tmpLayout)
                    self.right_top_list_view.setCellWidget(tmp_table_row, tmp_columncount, tmp_widget)
                else:
                    item = QTableWidgetItem(
                        str(self.right_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
                    item.setTextAlignment(Qt.AlignCenter)
                    self.right_top_list_view.setItem(tmp_table_row, tmp_columncount, item)
        header = self.right_top_list_view.horizontalHeader()
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)

        layout3 = QHBoxLayout()
        layout3.setAlignment(Qt.AlignVCenter)  # 垂直居中
        layout3.setContentsMargins(0, 0, 0, 0)
        layout3.addWidget(self.right_top_list_view)
        self.right_layout.addLayout(layout3,1)

    def changeTitle(self, state):
        rowNo = self.sender().getrowNo()
        info = self.right_list[rowNo]
        code = int(self.right_list[rowNo]['code'])
        if state:
            if code not in self.rule_list:
                self.rule_list.append(code)
            info['check'] = 0
            print('选择到了')
        else:
            if code in self.rule_list:
                self.rule_list.remove(code)
            print('没有选择')
            info['check'] = 1
        print(self.rule_list)

    def initRightBottonTable(self):
        self.right_bom_list_view = QTableWidget()
        stockDetaihorizontalHeader = ['期号', '编号', '位置', '号码', '单注', '手数','投注状态', '开奖', '结算', '方案模式']
        self.stockDetaihorizontalHeaderCode = ['qihao', 'code', 'position', 'number', 'one', 'count','state','open','caculate', 'mode']
        self.right_bom_list_view.setColumnCount(len(stockDetaihorizontalHeader))
        self.right_bom_list_view.setRowCount(len(self.right_botton_list))
        self.right_bom_list_view.setHorizontalHeaderLabels(stockDetaihorizontalHeader)
        self.right_bom_list_view.verticalHeader().setVisible(False)  # 隐藏垂直表头

        self.right_bom_list_view.setEditTriggers(QTableWidget.NoEditTriggers)
        self.right_bom_list_view.setSelectionMode(QTableWidget.SingleSelection)
        for tmp_table_row in range(self.right_bom_list_view.rowCount()):
            for tmp_columncount in range(self.right_bom_list_view.columnCount()):
                self.right_bom_list_view.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(
                    str(self.right_botton_list[tmp_table_row][self.stockDetaihorizontalHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.right_bom_list_view.setItem(tmp_table_row, tmp_columncount, item)

        layout3 = QHBoxLayout()
        layout3.setAlignment(Qt.AlignVCenter)  # 垂直居中
        layout3.setContentsMargins(0, 0, 0, 0)
        layout3.addWidget(self.right_bom_list_view)
        self.right_layout.addLayout(layout3,2)

    def freshLeftDom(self):
        """
        刷新左下
        :return:
        """
        self.stockDetailList.clearContents()
        self.stockDetailList.setRowCount(len(self.code_list))
        for tmp_table_row in range(self.stockDetailList.rowCount()):
            for tmp_columncount  in range(self.stockDetailList.columnCount()):
                self.stockDetailList.setRowHeight(tmp_table_row, 25)
                item = QTableWidgetItem(str(self.code_list[tmp_table_row][self.LeftTableHeaderCode[tmp_columncount]]))
                item.setTextAlignment(Qt.AlignCenter)
                self.stockDetailList.setItem(tmp_table_row,tmp_columncount, item)

    def freshRightTop(self):
        """
        刷新右上
        :return:
        """
        # self.right_top_list_view.clearContents()
        # self.right_top_list_view.setRowCount(len(self.right_list))
        for tmp_table_row in range(self.right_top_list_view.rowCount()):
            for tmp_columncount in range(self.right_top_list_view.columnCount()):
                if tmp_columncount == 4:
                    self.right_top_list_view.item(tmp_table_row, tmp_columncount).\
                        setText(str(self.right_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
                # self.right_top_list_view.setRowHeight(tmp_table_row, 25)
                # self.tmp_widget = QWidget()
                # self.tmpLayout = QHBoxLayout()
                # if tmp_columncount == 1:
                #     check = int(self.right_list[tmp_table_row].get('check', 1))
                #     cb_btn = MyCheckBox()
                #     self.tmpLayout.addWidget(cb_btn)
                #     cb_btn.setrowNo(tmp_table_row)
                #     cb_btn.clicked.connect(self.changeTitle)
                #     if check == 0:
                #         cb_btn.setChecked(True)
                #     else:
                #         cb_btn.setChecked(False)
                #     self.tmpLayout.setAlignment(Qt.AlignHCenter)
                #     self.tmpLayout.setContentsMargins(0, 0, 0, 0)
                #     self.tmp_widget.setLayout(self.tmpLayout)
                #     self.right_top_list_view.setCellWidget(tmp_table_row, tmp_columncount, self.tmp_widget)
                # else:
                #     item = QTableWidgetItem(
                #         str(self.right_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
                #     item.setTextAlignment(Qt.AlignCenter)
                #     self.right_top_list_view.setItem(tmp_table_row, tmp_columncount, item)
        # header = self.right_top_list_view.horizontalHeader()
        # header.setSectionResizeMode(6, QHeaderView.ResizeToContents)

    def update_left_bottom_view(self):
        # print( str(len(self.right_botton_list)) + '：：数据长度' )
        # for tmp_table_row in range(self.right_bom_list_view.rowCount()):
            # print(str(tmp_table_row)+ '行号：：：：')
            # for tmp_columncount in range(self.right_bom_list_view.columnCount()):
            #     if tmp_columncount == 8:
            #         self.right_top_list_view.item(tmp_table_row, tmp_columncount). \
            #             setText(str(self.right_botton_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
            #     elif tmp_columncount == 9:
            #         self.right_top_list_view.item(tmp_table_row, tmp_columncount). \
            #             setText(str(self.right_botton_list[tmp_table_row][self.right_topHeaderCode[tmp_columncount]]))
        if self.allupdate_right_boot:
            self.allupdate_right_boot = False
            self.right_bom_list_view.clearContents()
            self.right_bom_list_view.setRowCount(len(self.right_botton_list))
            for tmp_table_row in range(self.right_bom_list_view.rowCount()):
                for tmp_columncount in range(self.right_bom_list_view.columnCount()):
                    self.right_bom_list_view.setRowHeight(tmp_table_row, 25)
                    item = QTableWidgetItem(
                        str(self.right_botton_list[tmp_table_row][self.stockDetaihorizontalHeaderCode[tmp_columncount]]))
                    item.setTextAlignment(Qt.AlignCenter)
                    self.right_bom_list_view.setItem(tmp_table_row, tmp_columncount, item)
        elif self.addupdate_right_boot:
            for tmp_table_row in range(self.right_bom_list_view.rowCount()):
                print(str(tmp_table_row)+ '行号：：：：')
                self.addupdate_right_boot = False
                for tmp_columncount in range(self.right_bom_list_view.columnCount()):
                    if tmp_columncount == 7:
                        self.right_bom_list_view.item(tmp_table_row, tmp_columncount). \
                            setText(str(self.right_botton_list[tmp_table_row][self.stockDetaihorizontalHeaderCode[tmp_columncount]]))
                    elif tmp_columncount == 8:
                        self.right_bom_list_view.item(tmp_table_row, tmp_columncount). \
                            setText(str(self.right_botton_list[tmp_table_row][self.stockDetaihorizontalHeaderCode[tmp_columncount]]))



class MyCheckBox(QCheckBox):
    """
    交易列表详情按钮控件
    """
    def __init__(self):
        super(MyCheckBox, self).__init__()
        self.rowNo = 0

    def setParentWidget(self, parentWidget):
        self.parentWidget = parentWidget

    def setrowNo(self, rowNo):
        self.rowNo = rowNo

    def getrowNo(self):
        return self.rowNo


def main():
    try:
        if hasattr(sys, '_MEIPASS'):
            os.chdir(sys._MEIPASS)
        app = QApplication(sys.argv)
        ex = TransactionDetial()
        app.installEventFilter(ex)
        ex.show()
        sys.exit(app.exec_())
    except Exception as error:
        print(error)


if __name__ == '__main__':
    try:
        main()
    except Exception as edc:
        print(edc)
